package com.hksj.cbm.service;

import cn.hutool.core.map.MapUtil;
import com.hksj.cbm.mapper.DictionaryMapper;
import com.hksj.cbm.vo.DictionaryItemVO;
import com.hksj.cbm.vo.DictionaryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zengke
 * @version 1.0
 * @see DictionaryService
 * @since 2024/7/17 18:02
 */

@Service
public class DictionaryService {

    @Autowired
    private DictionaryMapper dictionaryMapper;

    //查询字典集合
    public Map<String, List<DictionaryItemVO>> queryDictionaryMap(){
        //查询字典明细列表
        List<DictionaryItemVO> dictionaryItemList = dictionaryMapper.queryDictionaryItemList();

        //字典明细为空直接返回空的map集合
        if (ObjectUtils.isEmpty(dictionaryItemList)){
            return MapUtil.empty();
        }

        //字典明细不为空,先构建字典明细树(字典明细树中顶级节点的parentId为null)
        List<DictionaryItemVO> dictionaryItemTree = getDictionaryItemChildren(null, dictionaryItemList);

        //将字典明细列表 以字典明细id为key转为map集合
        Map<String, List<DictionaryItemVO>> dictionaryItemMap = dictionaryItemTree.stream().collect(Collectors.groupingBy(DictionaryItemVO::getDictId));

        //返回查询结果
        return dictionaryItemMap;
    }

    public List<DictionaryItemVO> getDictionaryItemChildren(String parentId,List<DictionaryItemVO> dictionaryItemList){

        //查询字典明细树当前父节点对应的子节点集合
        List<DictionaryItemVO> childrenNode = dictionaryItemList.stream().filter(child -> Objects.equals(parentId, child.getParentId())).collect(Collectors.toList());

        //判断子节点是否为空
        if (ObjectUtils.isEmpty(childrenNode)){
            //若子节点为空则直接返回空的list集合
            return new ArrayList<>();
        }

        //子节点不为空
        //遍历子节点,获取每个子节点对应的孩子节点,将孩子节点设置到子节点中
        childrenNode.forEach(child ->{
            //现在子节点的id作为父id
            String cId = child.getId();

            //循环遍历拿到子节点的孩子节点
            List<DictionaryItemVO> cChildren = getDictionaryItemChildren(cId, dictionaryItemList);

            //把孩子节点设置到每个子节点中
            child.setChildren(cChildren);
        });

        //返回子节点集合
        return childrenNode;
    }

}
